import axios, {AxiosResponse} from "axios";
import {baseURL} from "../../config";
import LocalStorageUtil from "../../utils/local-storage-util";
import {Message} from 'element-ui';
import {MessageType} from "element-ui/types/message";
import store from '@/store';
import i18n from '@/i18n'
import Utils from "@/utils/utils";
import { SettingsGetterEnum } from "@/store/enum/store.enum";
import { ResponseStatusEnum } from "@/common/enum/common.enum";

import router from '@/router'

/*配置接收方式application/json;charset=UTF-8 或 application/x-www-form-urlencoded;charset=UTF-8*/
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
/*配置接口地址 接口地址在系统常量中配置*/
axios.defaults.baseURL = baseURL;
/*配置接口请求超时*/
axios.defaults.timeout = 120000;

axios.interceptors.request.use(
		config => {
			//请求的语言
			config.headers['Accept-Language'] = store.getters[SettingsGetterEnum.language];
			if (config.url.indexOf('auth/oauth/token') !== -1 || config.url.indexOf('dtk/user/loginByCode') !== -1) {
				// console.log(config.url.indexOf('auth/oauth/token'), '登录接口');
				config.headers['Authorization'] = 'Basic cGM6MjAxNzA4MDg=';
			} else {
				let token = LocalStorageUtil.getItem('token') || '';
				config.headers['Authorization'] = 'Bearer ' + token;
			}
			return config;
		},
		err => {
			return Promise.reject(err);
		});
// @ts-ignore
axios.interceptors.response.use(
		(res: AxiosResponse) => {
			/*对响应数据做处理*/
			// 如果http状态码不是200
			if (res.status !== ResponseStatusEnum.success) {
				conductRes(res.status, 'error', res.data, res);
			}
			//否则http状态码为200，但服务器返回的状态码不是200
			if (res.status === ResponseStatusEnum.success && res.data.status !== ResponseStatusEnum.success) {
				conductRes(res.data.status, 'warning', res.data.message, res);
			}
			return Promise.resolve(res);
		},
		error => {
			let messageText = '';
			let messageType: MessageType = 'error';
			/*if (error.code === 'ECONNABORTED') {//连接超时
				msg=i18n.t('tips.econnaborted') as string;
			}else */
			if (error.config.url.indexOf('fdsFile/getUrlPrefix') !== -1) {
				messageText = '文件路径前缀获取失败！';
				messageType = 'warning';
			} else if (!error.response) {//网络错误
				messageText = i18n.t('tips.networkError') as string;
			} else if (!error.response.data) {//服务器没有响应
				messageText = i18n.t('tips.noResponse') as string;
			} else {
				messageText = error.response.data.message || error.response.data;
			}
			message(messageText, messageType)
			return Promise.reject(error)// 返回接口返回的错误信息
		});
export default axios;

/**
 * 处理响应数据
 */
function conductRes(status: number, messageType: MessageType, messageText: string, res: AxiosResponse) {
	switch (status) {
			// 404
		case ResponseStatusEnum.notFound:
			messageText = i18n.t('tips.network404') as string;
			break;
			// 无权限401
		case ResponseStatusEnum.noAuth:
			messageText = i18n.t('tips.network401') as string;
			break;
			// 登录过期403
		case ResponseStatusEnum.authTimeout:
			messageText = i18n.t('tips.network403') as string;
			Utils.clearLoginInfo();
			// 延迟跳转，便于用户阅读弹窗信息
			setTimeout(() => {
				router.replace({name: 'login', query: {redirect: router.currentRoute.name}})
			}, 1500);
			break;
			// 直接强制跳登录页面-9998
		case ResponseStatusEnum.other:
			messageText = i18n.t('tips.serviceError') as string;
			Utils.clearLoginInfo();
			// 延迟跳转，便于用户阅读弹窗信息
			setTimeout(() => {
				router.replace({name: 'login', query: {redirect: router.currentRoute.name}})
			}, 1500);
			break;
		default:
			break;
	}
	message(messageText, messageType);
}

/**
 * message提示
 */
let messageObj;

function message(messageText: string, type: MessageType) {
	if (messageObj) {
		messageObj.close();
		messageObj = null;
	}
	messageObj = Message({message: messageText, type: type, showClose: true});
}
